#include "List.h"
ListNode*ListNodeBuy(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		printf("fail ListNodeBuy\n");
		return;
	}
	newnode->val = x;
	newnode->next = NULL;
	newnode->prev = NULL;	
	return newnode;
}
void ListInit(ListNode** pphead)
{
	assert(pphead);
	*pphead = ListNodeBuy(0);
	(*pphead)->next = *pphead;
	(*pphead)->prev = *pphead;
}
void ListPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = ListNodeBuy(x);
	ListNode* tail = phead->prev;
	newnode->next = phead;
	newnode->prev = tail;
	tail->next = newnode;
	phead->prev = newnode;
}
void ListPrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}
void ListPopBack(ListNode* phead)
{
	assert(phead);
	ListNode* tail = phead->prev;
	ListNode* tailprev = tail->prev;
	free(tail);
	tailprev->next = phead;
	phead->prev = tailprev;
}
void ListPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = ListNodeBuy(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
}
void ListPopFront(ListNode* phead)
{
	assert(phead);
	ListNode* front = phead->next;
	phead->next = front->next;
	front->next->prev = phead;
	free(front);
}
ListNode* ListFind(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->val == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
void ListInsertFront(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = ListNodeBuy(x);
	newnode->prev = pos->prev;
	newnode->next = pos;
	pos->prev->next = newnode;
	pos->prev = newnode;
}
void ListInsertAfter(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = ListNodeBuy(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}
void ListErase(ListNode* pos)
{
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}